package com.example.administrator.xiaobo.utils;

import android.os.Handler;

import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.io.IOException;

/**
 * Created by Administrator on 2017/2/8.
 */

public class OkHttpHelper {
    private static OkHttpClient okHttpClient;
    private Handler handler;
    private OkHttpHelper(){
        okHttpClient=new OkHttpClient();
        handler=new Handler();
    }
    public  static OkHttpHelper getInstance(){
        return new OkHttpHelper();
    }
    public void get(String url,BaseCallback callback){
        Request request=new Request.Builder().url(url).build();

        dorRequest(request,callback);
    }

    private void dorRequest(Request request, final BaseCallback callback) {
        callback.onBeforeRequest(request);
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
               callback.onFailure(request,e);
            }

            @Override
            public void onResponse(Response response) throws IOException {

                if (response.isSuccessful()){
                    String resultStr = response.body().string();
                    callbackSuccess(callback, resultStr);

                }else {
                    callbackError(callback, response);
                }
            }


        });
    }

    private void callbackError(final BaseCallback callback, final Response response) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                callback.onError(response, response.code());
            }
        });
    }

    private void callbackSuccess(final BaseCallback callback, final String resultStr) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                callback.onSuccess(resultStr);
            }
        });
    }

}
